const events = {}

function useEventBus() {
  const instanceEvent = {}
  const instance = getCurrentInstance()
  /**
   * 监听事件
   * @param key {string}
   * @param event {function}
   */
  function on(key, event) {
    if (!verifyKey) return
    if (!events[key]) {
      events[key] = []
    }
    if (instance) {
      if (!instanceEvent[key]) {
        instanceEvent[key] = []
      }
      instanceEvent[key].push(event)
    }
    events[key].push(event)
  }

  function once(key, event) {
    if (!verifyKey) return
    const fn = (...arg) => {
      event(arg)
      off(key, event)
    }
    on(key, fn)
  }

  function off(key, event) {
    if (!verifyKey) return
    if (event) {
      let index = instanceEvent[key].findIndex((e) => e === event)
      index > -1 && instanceEvent[key].splice(index, 1)
      index = events[key].findIndex((e) => e === event)
      index > -1 && events[key].splice(index, 1)
    } else {
      instanceEvent[key] = []
      events[key] = []
    }
  }

  /**
   * 触发事件
   * @param key {string}
   * @param params {any}
   */
  function emit(key, ...params) {
    if (!verifyKey) return
    events[key] && events[key].forEach((e) => e(...params))
  }

  if (instance) {
    onBeforeUnmount(() => {
      for (let key in instanceEvent) {
        instanceEvent[key].forEach((e) => {
          off(key, e)
        })
      }
    })
  }

  return {
    on,
    once,
    off,
    emit,
  }
}

function verifyKey(key) {
  if (key === '') {
    console.warn(`[eventBus]: The key cannot be ''`)
    return false
  } else if (typeof key !== 'string') {
    console.warn(`[eventBus]: The type of key should be string, but the result is ${typeof key}`)
    return false
  }
  return true
}

export default useEventBus
